package com.haitaoit.chengquan.module.home.activity.maintenance;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center_service.model.ServiceEvaluateModel;
import com.haitaoit.chengquan.module.home.activity.maintenance.adapter.MaintenanceDetailAdapter;
import com.haitaoit.chengquan.module.home.activity.maintenance.adapter.MaintenanceEvaAdapter;
import com.haitaoit.chengquan.module.home.activity.maintenance.adapter.MaintenanceServerAdapter;
import com.haitaoit.chengquan.module.home.model.MaintenanceDetailModel;
import com.haitaoit.chengquan.module.home.model.MaintenanceServerModel;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.CircleImageView;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.MyWebView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MaintenanceDetailActivity2 extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pullrefreshscrollview)
    PullToRefreshScrollView pullrefreshscrollview;
    @ViewInject(R.id.right)
    RelativeLayout right;

    private ScrollView mScrollView;
    private LinearLayout null_information_layout;
    private MyListView listView;
    private CircleImageView center_img;
    private TextView real_name, service_scope, address, volume_count;
    private MyWebView webview;
    private RadioButton introduce_show;

    private boolean isFrist = true;
    private int page = 1, show_type = 1;

    private String id;
    private MaintenanceDetailModel model;
    private MaintenanceEvaAdapter evaAdapter;
    private MaintenanceServerAdapter serverAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.pullrefreshscollview);
//        setContentView(R.layout.activity_maintenance_detail2);
        ViewUtils.inject(this);
        setLeftShow(1, R.mipmap.left);
        setRightShow(1, R.mipmap.pic37_1);
        setTitle_V(getString(R.string.MaintenanceDetail_title));
        backLeft_V();


        View view = LayoutInflater.from(this).inflate(R.layout.activity_maintenance_detail2, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);
        center_img = (CircleImageView) view.findViewById(R.id.center_img);
        real_name = (TextView) view.findViewById(R.id.real_name);
        service_scope = (TextView) view.findViewById(R.id.service_scope);
        address = (TextView) view.findViewById(R.id.address);
        volume_count = (TextView) view.findViewById(R.id.volume_count);
        webview = (MyWebView) view.findViewById(R.id.webview);
        introduce_show = (RadioButton) view.findViewById(R.id.introduce_show);
        view.findViewById(R.id.detail_show).setOnClickListener(listener);
        view.findViewById(R.id.introduce_show).setOnClickListener(listener);
        view.findViewById(R.id.eva_show).setOnClickListener(listener);
        view.findViewById(R.id.server_show).setOnClickListener(listener);

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(false);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        id = getIntent().getStringExtra("id");
        evaAdapter = new MaintenanceEvaAdapter(this);
        serverAdapter = new MaintenanceServerAdapter(this);
        webview.setVisibility(View.VISIBLE);

//        http://cqapi.hai-tao.net/Help/Api/GET-api-Maintenance-Getmer_model-id_user_id_sign
        httpGetmer_model();
        WebSettings seting=webview.getSettings();
        seting.setJavaScriptEnabled(true);
        webview.setWebChromeClient(new WebChromeClient(){

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);

                if (newProgress==100){
                    hideProgree();
                }else {

                    showProgrees("");
                }
            }

        });
    }

    @OnClick({R.id.right})
    public void onClick(View v) {
        if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("tag", "0");
            startActivity(intent);
        } else if (PreferenceUtils.getPrefString("account_type", "").equals("1")) {
            httpGetmer_collection();
        } else {
            ToastUtils.showToast("该账号不是需求商！");
        }
        super.onClick(v);
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.detail_show:// 详情
                    show_type = 1;
                    null_information_layout.setVisibility(View.GONE);
                    listView.setVisibility(View.GONE);
                    webview.setVisibility(View.VISIBLE);
                    break;
                case R.id.introduce_show:// 资质
                    show_type = 1;
                    webview.setVisibility(View.GONE);
                    if (model.getQualification_introduced() == null || model.getQualification_introduced().size() == 0) {
                        listView.setVisibility(View.GONE);
                        null_information_layout.setVisibility(View.VISIBLE);
                    } else {
                        listView.setVisibility(View.VISIBLE);
                        MaintenanceDetailAdapter adapter = new MaintenanceDetailAdapter(MaintenanceDetailActivity2.this);
                        adapter.setList(model.getQualification_introduced());
                        listView.setAdapter(adapter);
                    }
                    mScrollView.smoothScrollTo(0, 0);
                    break;
                case R.id.eva_show:// 评价
                    webview.setVisibility(View.GONE);
                    isFrist = true;
                    page = 1;
                    show_type = 2;
                    listView.setAdapter(evaAdapter);
                    httpGetmer_evaluation_list();
                    break;
                case R.id.server_show:// 服务项目
                    webview.setVisibility(View.GONE);
                    isFrist = true;
                    page = 1;
                    show_type = 3;
                    listView.setAdapter(serverAdapter);
                    httpGetmer_service_list2();
                    break;
            }
        }
    };

    private void httpGetmer_model() {
        String user_id = PreferenceUtils.getPrefString("user_id", "");
        if ("".equals(user_id))
            user_id = "0";
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("id", id));
        list.add(new NameValuePairSign("user_id", user_id));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("user_id", user_id);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getmer_model, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            model = gson.fromJson(Response, MaintenanceDetailModel.class);
                            ImageLoader.getInstance().displayImage(model.getHead_portrait(), center_img);
                            real_name.setText(model.getReal_name());
                            service_scope.setText(model.getService_scope());
                            address.setText("所在地区：" + model.getAddress());
                            volume_count.setText("成交量：" + model.getVolume_count() + "家");
                            webview.loadDataWithBaseURL("about:blank", model.getCompany_introduction(), "text/html", "utf-8", null);



                            // is_collection:1未收藏2已收藏 group_id://1个人商户2企业商户
                            if (model.getIs_collection().equals("1")) {
                                setRightShow(1, R.mipmap.pic37_1);
                            } else if (model.getIs_collection().equals("2")) {
                                setRightShow(1, R.mipmap.pic37_2);
                            }

                            //TODO:不知道到底有没有资质介绍

//                            if (model.getGroup_id().equals("1")) {
//                                introduce_show.setVisibility(View.GONE);
//                            } else {
//                                introduce_show.setVisibility(View.VISIBLE);
//                            }
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 收藏
    private void httpGetmer_collection() {
        final List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("id", id));
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        final RequestParams params = new RequestParams();
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getmer_collection, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            JSONObject js = new JSONObject(Response);
                            String type = js.getString("type");
                            if (type.equals("1")) {
                                setRightShow(1, R.mipmap.pic37_1);
                            } else if (type.equals("2")) {
                                setRightShow(1, R.mipmap.pic37_2);
                            }
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 评价信息
    private void httpGetmer_evaluation_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", id));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", id);
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getmer_evaluation_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<ServiceEvaluateModel> new_list = new ArrayList<ServiceEvaluateModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<ServiceEvaluateModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<ServiceEvaluateModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<ServiceEvaluateModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            evaAdapter.setList(new_list);
                            evaAdapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<ServiceEvaluateModel> allList = evaAdapter.getList();
                        allList.addAll(new_list);
                        evaAdapter.setList(allList);
                        evaAdapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 服务项目
    private void httpGetmer_service_list2() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("mer_id", id));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("mer_id", id);
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getmer_service_list2, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<MaintenanceServerModel> new_list = new ArrayList<MaintenanceServerModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<MaintenanceServerModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<MaintenanceServerModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<MaintenanceServerModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            serverAdapter.setList(new_list);
                            serverAdapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<MaintenanceServerModel> allList = serverAdapter.getList();
                        allList.addAll(new_list);
                        serverAdapter.setList(allList);
                        serverAdapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        if (show_type == 1) {
            pullrefreshscrollview.onPullUpRefreshComplete();
        } else if (show_type == 2) {
            httpGetmer_evaluation_list();
        } else if (show_type == 3) {
            httpGetmer_service_list2();
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        if (show_type == 1) {
            pullrefreshscrollview.onPullUpRefreshComplete();
        } else if (show_type == 2) {
            httpGetmer_evaluation_list();
        } else if (show_type == 3) {
            httpGetmer_service_list2();
        }
    }
}
